<?php

namespace DreamCat\FrameCore\HttpHandle;

use DreamCat\FrameInterface\Factory\ControllerFactory;
use DreamCat\FrameInterface\HttpHandle\ErrorHandle;
use DreamCat\FrameInterface\HttpHandle\HttpRequestProcess;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\HttpHandlerRunner\Emitter\EmitterInterface;

/**
 * 默认的http请求处理主流程
 * @author vijay
 */
class DefaultHttpRequestProcess implements HttpRequestProcess
{
    /**
     * @Autowire
     * @var EmitterInterface 响应处理器
     */
    private $emitter;
    /**
     * @Autowire
     * @var ControllerFactory
     */
    private $httpHandle;

    /**
     * @Autowire
     * @var ServerRequestInterface 请求对象
     */
    private $request;

    /**
     * @return EmitterInterface 响应处理器
     */
    public function getEmitter(): \Zend\HttpHandlerRunner\Emitter\EmitterInterface
    {
        return $this->emitter;
    }

    /**
     * @param EmitterInterface $emitter 响应处理器
     * @return static 对象本身
     */
    public function setEmitter(\Zend\HttpHandlerRunner\Emitter\EmitterInterface $emitter): DefaultHttpRequestProcess
    {
        $this->emitter = $emitter;
        return $this;
    }

    /**
     * @return ControllerFactory
     */
    public function getHttpHandle(): \DreamCat\FrameInterface\Factory\ControllerFactory
    {
        return $this->httpHandle;
    }

    /**
     * @param ControllerFactory $httpHandle
     * @return static 对象本身
     */
    public function setHttpHandle(ControllerFactory $httpHandle): DefaultHttpRequestProcess
    {
        $this->httpHandle = $httpHandle;
        return $this;
    }

    /**
     * @return ServerRequestInterface 请求对象
     */
    public function getRequest(): ServerRequestInterface
    {
        return $this->request;
    }

    /**
     * @param ServerRequestInterface $request 请求对象
     * @return static 对象本身
     */
    public function setRequest(ServerRequestInterface $request): DefaultHttpRequestProcess
    {
        $this->request = $request;
        return $this;
    }

    /**
     * 处理请求
     * @param ContainerInterface $container 容器
     * @return void
     */
    public function handle(ContainerInterface $container): void
    {
        try {
            $response = $this->getHttpHandle()->httpHandle($container, $this->getRequest());
        } catch (\Throwable $throwable) {
            /** @var ErrorHandle $errorHandle */
            $errorHandle = $container->get(ErrorHandle::class);
            $response = $errorHandle->handle($throwable);
        }
        $this->getEmitter()->emit($response);
    }
}

# end of file
